<template>
  <div>
    <div class="mb-3">
      <el-button type="primary" plain size="small" v-if="!hasFinish" @click="onFinishCencus">
        <i class="fa fa-check-circle"></i>
        完成报告
      </el-button>
      <el-button type="primary" plain size="small" @click="getData()">
        <i class="fa fa-refresh"></i>
        刷新
      </el-button>
      <el-button type="primary" plain size="small" @click="onPrint">
        <i class="fa fa-print"></i>
        打印
      </el-button>
    </div>

    <div v-loading="loading" class="card">
      <div class="card-body">
        <div
          class="report-body"
          id="report-census"
          style="
            font-family: SimSun;
            font-size: 1.5rem;
            line-height: 2;
            max-width: 842px;
            margin: 0 auto;
          "
        >
          <div style="page-break-after: always">
            <div
              style="
                font-size: 1.25rem;
                font-family: SimSun;
                margin-bottom: 16rem;
                display: flex;
                justify-content: flex-end;
              "
            >
              <span>项目编号：</span>
              <div v-if="!hasFinish" class="d-flex" style="max-width: 200px">
                <span>{{ censusNumberPrefix }}</span>
                <span>-</span>
                <input
                  style="
                    display: inline-block;
                    padding: 0;
                    border: none;
                    background-color: #ffffee;
                    width: 60px;
                    text-align: center;
                    font-size: 1.5rem;
                  "
                  class="form-control"
                  placeholder="XXXX"
                  v-model="censusNumberYear"
                  @input="onCensusNumberYearInput"
                  @blur="onCensusNumberYearBlur"
                />
                <span>-</span>
                <input
                  style="
                    display: inline-block;
                    padding: 0;
                    border: none;
                    background-color: #ffffee;
                    width: 50px;
                    text-align: center;
                    font-size: 1.5rem;
                  "
                  class="form-control"
                  placeholder="XXX"
                  ref="censusNumberSerial"
                  v-model="censusNumberSerial"
                  @input="onCensusNumberSerialInput"
                  @blur="onCensusNumberSerialBlur"
                  @keyup.enter.stop="$refs.loadMainEntity.focus()"
                />
              </div>
              <span v-else>{{ dataCensus.census_number }}</span>
            </div>

            <h2
              style="
                font-family: SimHei;
                margin-bottom: 16rem;
                text-align: center;
                font-size: 2.5rem;
              "
            >
              调查报告
            </h2>

            <div style="font-family: SimHei; margin-bottom: 20rem">
              <div class="row mb-3">
                <div class="col-5 text-right">申请人名称:</div>
                <div class="col-7">
                  <el-input
                    v-if="!hasFinish"
                    ref="loadMainEntity"
                    style="max-width: 300px; font-size: 1.5rem"
                    v-model="dataCensus.load_main_entity"
                    @blur="saveCensusData('load_main_entity')"
                  ></el-input>
                  <span v-else>{{ dataCensus.load_main_entity }}</span>
                </div>
              </div>
              <div class="row mb-3">
                <div class="col-5 text-right">调项目经理:</div>
                <div class="col-7">
                  <span>{{ dataRelatedView.res_a_name }}、{{ dataRelatedView.res_b_name }}</span>
                </div>
              </div>
              <div class="row mb-3">
                <div class="col-5 text-right">调 查 时 间:</div>
                <div class="col-7">
                  <el-date-picker
                    v-if="!hasFinish"
                    style="width: 300px; font-size: 1.25rem"
                    v-model="dataCensus.survey_date"
                    value-format="yyyy-MM-dd"
                    @change="saveCensusData('survey_date')"
                  ></el-date-picker>
                  <span v-else>
                    {{ $utils.dateFormat(dataCensus.survey_date, 'yyyy年M月d日') }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div style="page-break-after: always">
            <p style="text-indent: 3rem">
              <span>{{ dataCensus.load_main_entity }}</span>
              <span>于</span>
              <span>{{ $utils.dateFormat(dataRelatedView.create_time, 'yyyy年M月d日') }}</span>
              <span>向我公司申请贷款担保</span>
              <span>{{ dataRelatedView.approved_funds || '-' }}万元，期限</span>
              <span>
                <input
                  v-if="!hasFinish"
                  style="
                    max-width: 40px;
                    display: inline;
                    padding: 0 2px;
                    height: 30px;
                    font-size: 1.5rem;
                  "
                  type="number"
                  step="1"
                  class="form-control"
                  v-model="dataCensus.warranty_period"
                  @blur="saveCensusData('warranty_period')"
                />
                <span v-else>{{ dataCensus.warranty_period }}</span>
              </span>
              <span>年，经初步了解，申请人基本符合条件，我公司</span>
              <span>{{ dataRelatedView.res_a_name }}、{{ dataRelatedView.res_b_name }}</span>
              <span>于</span>
              <span>{{ $utils.dateFormat(dataCensus.survey_date, 'yyyy年M月d日') }}</span>
              <span>
                对申请人的经营情况、家庭情况、担保贷款用途等情况进行了实地调查，现将调查情况报告如下：
              </span>
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              一、申请人基本情况
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.base_info"
              style="font-size: 1.5rem"
              @blur="saveCensusData('base_info')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.base_info }}
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              二、申请人经营情况
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.business_des"
              style="font-size: 1.5rem"
              @blur="saveCensusData('business_des')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.business_des }}
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              三、担保贷款用途调查
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.borrowing_reason"
              style="font-size: 1.5rem"
              @blur="saveCensusData('borrowing_reason')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.borrowing_reason }}
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              四、申请人还款能力分析
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.repayment_plan"
              style="font-size: 1.5rem"
              @blur="saveCensusData('repayment_plan')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.repayment_plan }}
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              五、反担保措施分析
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.counter_guarantee_evaluation"
              style="font-size: 1.5rem"
              @blur="saveCensusData('counter_guarantee_evaluation')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.counter_guarantee_evaluation }}
            </p>

            <h3 style="font-weight: bold; margin-top: 2rem; font-size: 1.5rem">
              六、风险评价及调查结论
            </h3>

            <el-input
              v-if="!hasFinish"
              type="textarea"
              v-model="dataCensus.project_risk_analysis"
              style="font-size: 1.5rem"
              @blur="saveCensusData('project_risk_analysis')"
            ></el-input>
            <p class="border p-3" style="text-indent: 3rem" v-else>
              {{ dataCensus.project_risk_analysis }}
            </p>

            <h3 style="font-weight: bold; margin: 5rem 0 2rem 0; font-size: 1.5rem">
              调查结论及意见：
            </h3>

            <table class="table table-bordered mb-5" style="vercti">
              <colgroup>
                <col width="30%" />
                <col width="70%" />
              </colgroup>
              <tbody>
                <tr>
                  <td class="text-center" style="vertical-align: middle">调查员A角意见：</td>
                  <td>
                    <el-input
                      v-if="!hasFinish"
                      type="textarea"
                      :rows="1"
                      v-model="dataCensus.a_opinion"
                      style="font-size: 1.5rem"
                      @blur="saveCensusData('a_opinion')"
                    ></el-input>
                    <p style="text-indent: 3rem" v-else>
                      {{ dataCensus.a_opinion }}
                    </p>
                    <div class="row" style="line-height: 1.5">
                      <div class="col text-center">签字：</div>
                      <div class="col text-center">日期：</div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td class="text-center" style="vertical-align: middle">调查员B角意见：</td>
                  <td>
                    <el-input
                      v-if="!hasFinish"
                      type="textarea"
                      :rows="1"
                      v-model="dataCensus.b_opinion"
                      style="font-size: 1.5rem"
                      @blur="saveCensusData('b_opinion')"
                    ></el-input>
                    <p style="text-indent: 3rem" v-else>
                      {{ dataCensus.b_opinion }}
                    </p>
                    <div class="row" style="line-height: 1.5">
                      <div class="col text-center">签字：</div>
                      <div class="col text-center">日期：</div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td class="text-center" style="vertical-align: middle">业务部负责人意见：</td>
                  <td>
                    <el-input
                      v-if="!hasFinish"
                      type="textarea"
                      :rows="1"
                      v-model="dataCensus.approval_option"
                      style="font-size: 1.5rem"
                      @blur="saveCensusData('approval_option')"
                    ></el-input>
                    <p style="text-indent: 3rem" v-else>
                      {{ dataCensus.approval_option }}
                    </p>
                    <div class="row" style="line-height: 1.5">
                      <div class="col text-center">签字：</div>
                      <div class="col text-center">日期：</div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div style="page-break-after: always">
            <h3 class="report-section-title">附件</h3>

            <div v-if="!hasFinish">
              <upload-oss
                multiple
                accept="image/*"
                listType="picture-card"
                :limit="4"
                :file-list="attachFileList"
                :on-complete="handleImagesComplete"
                :on-exceed="handleOnExceed"
                :on-remove="handleRemove"
                auto-upload
                ref="attachOss"
              ></upload-oss>
            </div>

            <div v-else>
              <div v-for="(img, index) in attachFileList" :key="index" class="mb-1 text-center">
                <img :src="img.url" alt="附件图片" height="400" style="max-width: 100%" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { printHtml, arrayFromString } from '@vimi/utils-tool'

const CREDIT_SERVER = 'credit'
const yearNow = new Date().getFullYear()

export default {
  components: {},
  props: {
    viewMode: Boolean,
    relatedId: String,
  },
  data() {
    return {
      customerRelatedId: '',
      loading: false,
      dataRelatedView: {},
      dataRelatedViewSolid: {},
      censusTableName: 'credit_census_report_simple',
      dataCensus: {},
      dataCenSusSolid: {},

      // 编号
      censusNumberPrefix: 'TDC',
      censusNumberYear: '',
      censusNumberSerial: '',

      // 附件
      attachFileList: [],
    }
  },
  computed: {
    hasFinish() {
      return this.dataCensus.census_status === '2' || this.viewMode
    },
    clientId() {
      return this.$store.getters.org.clientId
    },
  },
  watch: {
    relatedId() {
      this.init()
    },
  },
  created() {
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      this.customerRelatedId = this.relatedId || this.$route.query.id
      this.getData()
    },

    async getData() {
      this.loading = true
      Promise.all([this.getRelatedView(), this.getCensusSimple()])
        .then(async () => {
          // 默认同步贷款主体名称和期限
          const data = {}
          let needSync = false
          if (!this.dataCensus.load_main_entity) {
            needSync = true
            data.load_main_entity = this.dataRelatedView.customer_name
          }
          if (!this.dataCensus.warranty_period) {
            needSync = true
            data.warranty_period = this.dataRelatedView.load_years
          }
          if (needSync) {
            if (this.dataCensus.id) {
              await this.$utils.promise(
                this.$api.updateData(CREDIT_SERVER, this.censusTableName, this.dataCensus.id, data)
              )
            } else {
              data.service_id = this.clientId
              data.customer_related_id = this.customerRelatedId
              await this.$utils.promise(
                this.$api.addData(CREDIT_SERVER, this.censusTableName, data)
              )
            }
            this.getCensusSimple()
          }
        })
        .catch(() => {
          this.$message.error('获取数据失败，请刷新重试！')
        })
        .then(() => {
          this.loading = false
        })
    },

    // 关联基本信息
    async getRelatedView() {
      // eslint-disable-next-line
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.promise(
          this.$api.getData(CREDIT_SERVER, 'customer_related_base_view', {
            'customer_related_id.eq': this.customerRelatedId,
          })
        )
        if (res) {
          this.dataRelatedView = (res.data && res.data.length && res.data[0]) || {}
          this.dataRelatedViewSolid = { ...this.dataRelatedView }
          resolve()
        } else {
          reject(err)
        }
      })
    },

    // 简易报告信息
    async getCensusSimple() {
      this.censusNumberYear = ''
      this.censusNumberSerial = ''
      // eslint-disable-next-line
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.promise(
          this.$api.getData(CREDIT_SERVER, this.censusTableName, {
            'customer_related_id.eq': this.customerRelatedId,
          })
        )
        if (res) {
          this.dataCensus = (res.data && res.data.length && res.data[0]) || {}
          this.dataCenSusSolid = { ...this.dataCensus }

          // 编号
          if (this.dataCensus.census_number) {
            const arr = this.dataCensus.census_number.split('-')
            if (arr.length > 2) {
              this.censusNumberYear = arr[1]
              this.censusNumberSerial = arr[2]
            }
          }

          // 附件图片
          this.attachFileList = arrayFromString(this.dataCensus.attachment).map(item => {
            return { name: '', url: item }
          })
          resolve()
        } else {
          reject(err)
        }
      })
    },

    async saveCensusData(key) {
      // eslint-disable-next-line
      return new Promise(async resolve => {
        if (this.dataCensus[key] !== this.dataCenSusSolid[key]) {
          let data = {}
          data[key] = this.dataCensus[key]
          if (this.dataCensus.id) {
            let [res, err] = await this.$utils.promise(
              this.$api.updateData(CREDIT_SERVER, this.censusTableName, this.dataCensus.id, data)
            )
            if (res) {
              // this.$message.success('数据采集成功！')
              this.getCensusSimple()
              resolve()
            } else {
              this.$message.error(`修改失败，请重试！（${err.status}）`)
            }
          } else {
            data.customer_related_id = this.customerRelatedId
            const [res, err] = await this.$utils.promise(
              this.$api.addData(CREDIT_SERVER, this.censusTableName, data)
            )
            if (res) {
              // this.$message.success('数据采集成功！')
              this.getCensusSimple()
              resolve()
            } else {
              this.$message.error(`修改失败，请重试！（${err.status}）`)
            }
          }
        } else {
          resolve()
        }
      })
    },

    onFinishCencus() {
      this.$msgbox({
        title: '提示',
        message: '确定完成报告（请确认信息已保存，完成后将不能再修改）？',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '完成中...'
            const [res] = await this.$utils.promise(
              this.$api.updateData(CREDIT_SERVER, this.censusTableName, this.dataCensus.id, {
                census_status: 2,
              })
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'

            if (res) {
              this.$message.success('完成调查报告成功！')
              this.getCensusSimple()
              done()
            } else {
              this.$message.error('提交失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    getImageString(images = []) {
      return images && images.length ? `["${images.map(item => item.url).join('","')}"]` : ''
    },

    handleImagesComplete(images) {
      this.dataCensus.attachment = this.getImageString(images)
      this.saveCensusData('attachment')
    },

    handleOnExceed() {
      this.$message.error('附件图片最多四张！')
    },

    handleRemove(file, fileList) {
      this.dataCensus.attachment = this.getImageString(fileList)
      this.saveCensusData('attachment')
    },

    onPrint() {
      printHtml(document.getElementById('report-census').innerHTML, '')
    },

    onCensusNumberYearInput() {
      this.censusNumberYear = this.censusNumberYear.replace(/[^0-9]+/g, '')
      if (this.censusNumberYear.length > 4) {
        const lastChar = this.censusNumberYear[4]
        this.censusNumberYear = this.censusNumberYear.replace(/^(\d{4}).*/, '$1')
        this.$refs.censusNumberSerial.focus()
        if (!this.censusNumberSerial) {
          this.censusNumberSerial = lastChar
        }
      }
      if (this.censusNumberYear.length === 4) {
        const year = +this.censusNumberYear
        if (year > yearNow || year < yearNow - 1) {
          this.$message.error('编号年份必须是今年或去年！')
        }
      }
    },

    onCensusNumberSerialInput() {
      this.censusNumberSerial = this.censusNumberSerial.replace(/[^0-9]+/g, '')
      if (this.censusNumberSerial.length > 3) {
        this.censusNumberSerial = this.censusNumberSerial.replace(/^\d(\d{3}).*/, '$1')
      }
      if (this.censusNumberSerial === '000') {
        this.$message.error('编号必须大于0')
      }
    },

    onCensusNumberYearBlur() {
      if (!this.censusNumberYear) {
        return this.$message.error('请输入编号年份！')
      }
      const year = +this.censusNumberYear
      if (year > yearNow || year < yearNow - 1) {
        return this.$message.error('编号年份必须是今年或去年！')
      }
      if (this.censusNumberSerial) {
        if (this.censusNumberSerial === '000') {
          return this.$message.error('编号必须大于0')
        }
        this.goSaveCensusNumber()
      }
    },

    onCensusNumberSerialBlur() {
      if (!this.censusNumberSerial) {
        return this.$message.error('请输入项目序号！')
      }
      if (this.censusNumberSerial === '000') {
        return this.$message.error('编号必须大于0')
      }
      if (this.censusNumberYear) {
        const year = +this.censusNumberYear
        if (year > yearNow || year < yearNow - 1) {
          return this.$message.error('编号年份必须是今年或去年！')
        }
        this.goSaveCensusNumber()
      }
    },

    goSaveCensusNumber() {
      const num = `${this.censusNumberPrefix}-${
        this.censusNumberYear
      }-${this.getFullNumberSerial()}`

      if (num === this.dataCenSusSolid.census_number) {
        return
      }

      this.validateCensusNumberFromRemote(num).then(res => {
        if (res === 2) {
          this.dataCensus.census_number = num
          this.saveCensusData('census_number')
        } else if (res === 1) {
          this.$message.error('项目编号已经存在！')
        }
      })
    },

    getFullNumberSerial() {
      return Array(3 - this.censusNumberSerial.length).join('0') + this.censusNumberSerial
    },

    validateCensusNumberFromRemote(num) {
      // eslint-disable-next-line
      return new Promise(async resolve => {
        const [res, err] = await this.$utils.promise(
          this.$api.getData(CREDIT_SERVER, this.censusTableName, {
            'customer_related_id.eq': this.customerRelatedId,
            'census_number.eq': num,
          })
        )
        if (err) {
          this.$message.error('项目编号远程验证失败！')
          resolve(0)
        } else if (res && res.data && res.data.length) {
          resolve(1)
        } else {
          resolve(2)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped></style>
